import { Injectable } from "@angular/core";
import { WebsocketMessage, WebsocketService } from "./websocket";
import { Subject } from "rxjs";

@Injectable({
    providedIn: 'root',
})
export class ControlService {
    private websocket: WebsocketService;

    public get is_init(): boolean {
        return this.websocket.is_connected
    }

    public on_screen_info: Subject<ScreenInfo> = new Subject();

    constructor() {
        this.websocket = new WebsocketService();
        this.websocket.subject.subscribe((msg: WebsocketMessage) => {
            this.handle(msg);
        });
    }

    init(url: string) {
        if (url)
            this.websocket.connect(url);
    }

    private handle(msg: WebsocketMessage) {
        switch (msg.type) {
            case DataEvent.ScreenInfo: {
                this.on_screen_info.next(msg.data);
                break;
            }
        }
    }


    public on_key_event(event: KeyboardEvent) {
        let data = {
            type: event.type,
            key: event.key,
            code: event.code,
            ctrl_key: event.ctrlKey,
            alt_key: event.altKey,
            shift_key: event.shiftKey,
            repeat: event.repeat,
            meta_key: event.metaKey,
        }
        console.log("键盘事件", data)
        this.websocket.send({
            type: DataEvent.KeyboardEvent,
            data: data
        })
    }

    public on_mouse_wheel(event: WheelEvent) {
        let msg = {
            type: DataEvent.MouseEvent, data: {
                type: event.type,
                delta_x: event.deltaX,
                delta_y: event.deltaY,
            }
        }
        this.websocket.send(msg)
    }

    public on_mouse_event(event: MouseEvent) {
        let msg = {
            type: DataEvent.MouseEvent, data: {
                type: event.type,
                offset_x: event.offsetX,
                offset_y: event.offsetY,
                button: event.button
            }
        }

        this.websocket.send(msg)
    }

    public get_screen_info() {
        this.websocket.send({ type: DataEvent.ScreenInfo, data: null })
    }

}

export enum DataEvent {
    /**键盘按下事件 */
    KeyboardEvent = "keyboard-event",
    /**鼠标事件 */
    MouseEvent = "mouse-event",
    /**屏幕信息 */
    ScreenInfo = "screen-info"
}

export interface ScreenInfo {
    screen_list: Screen[]
}

export interface Screen {
    resolution_ratio: ResolutionRatio;
}
export interface ResolutionRatio {
    width: number
    height: number
}